package Connection;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Time;

import com.thoughtworks.xstream.XStream;

import Controller.Game.GamePanelController;

public class ServerConectionThread extends Thread{

	private ServerSocket server;
	private Socket client;
	private ObjectInputStream reader;
	private String xml;
	private GamePanelController control;

	public ServerConectionThread(GamePanelController principalControl, int port) {
		// TODO Auto-generated constructor stub
		//instancing
		xml = new String();
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		control = principalControl;

	}

	public void run() {
		// TODO Auto-generated method stub
		while (true) {
			try {
				client = server.accept();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				//e1.printStackTrace();
				System.out.print("pau aki");
			}
			try {
				reader = new ObjectInputStream(client.getInputStream());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				xml = (String)reader.readObject();
				System.out.println(xml);
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (ClassNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			control.cmdParse(xml);
			try {
				client.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				reader.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
}
